package com.cf;

import com.cf.timer.ExpirationTask;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * game-server-Bindthread
 * <p>
 * 任务会由指定的线程完成！
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/5/7 下午 07:07
 */
@Slf4j
public class BindThreadPool {

    private static BindThreadPool instance;

    private List<ExecutorService> workers = new ArrayList<>();

    private BindThreadPool(int times) {
        int availableProcessors = Runtime.getRuntime().availableProcessors() * times;
        for (int start = 0; start < availableProcessors; start++) {
            workers.add(Executors.newSingleThreadExecutor());
        }
    }

    static {
        instance = new BindThreadPool(2);
    }

    public static BindThreadPool getInstance() {
        return instance;
    }

    public void run(ExpirationTask task) {
        int workerFlag = Math.abs(task.getTaskDispatchId().hashCode() % workers.size());
        log.info("获取第【{}】个worker，干活", workerFlag);
        workers.get(workerFlag).execute(task);
    }

}
